// 登录表单处理
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const predictionForm = document.getElementById('predictionForm');
    const logoutBtn = document.getElementById('logoutBtn');
    const loginMessage = document.getElementById('loginMessage');
    const submitBtn = document.getElementById('submitBtn');
    const btnText = document.querySelector('.btn-text');
    
    // 登录功能
    if (loginForm) {
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showMessage(loginMessage, '登录成功，正在跳转...', 'success');
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);
                } else {
                    showMessage(loginMessage, data.message, 'error');
                }
            } catch (error) {
                showMessage(loginMessage, '登录请求失败，请稍后重试', 'error');
            }
        });
    }
    
    // 预测功能
    if (predictionForm) {
        predictionForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 显示加载状态
            submitBtn.disabled = true;
            btnText.textContent = '计算中...';
            if (!submitBtn.querySelector('.loading')) {
                const loadingEl = document.createElement('span');
                loadingEl.className = 'loading';
                submitBtn.prepend(loadingEl);
            }
            
            // 收集表单数据
            const formData = new FormData(predictionForm);
            const data = {};
            formData.forEach((value, key) => {
                data[key] = parseFloat(value);
            });
            
            try {
                const response = await fetch('/predict', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayResults(result);
                } else {
                    alert('预测失败: ' + result.message);
                }
            } catch (error) {
                alert('请求失败，请稍后重试');
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                btnText.textContent = '计算信用评分';
                const loadingEl = submitBtn.querySelector('.loading');
                if (loadingEl) {
                    loadingEl.remove();
                }
            }
        });
    }
    
    // 退出功能
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            if (confirm('确定要退出登录吗？')) {
                fetch('/logout', { method: 'POST' })
                    .then(() => {
                        window.location.href = '/login';
                    });
            }
        });
    }
    
    // 显示消息函数
    function showMessage(element, message, type) {
        element.textContent = message;
        element.className = `message ${type}`;
        element.classList.remove('hidden');
        
        // 5秒后隐藏消息
        setTimeout(() => {
            element.classList.add('hidden');
        }, 5000);
    }
    
    // 显示结果函数
    function displayResults(result) {
        const resultCard = document.getElementById('resultCard');
        const creditScore = document.getElementById('creditScore');
        const delinquentStatus = document.getElementById('delinquentStatus');
        const riskFill = document.querySelector('.risk-fill');
        const riskConclusion = document.getElementById('riskConclusion');
        
        // 更新结果值
        creditScore.textContent = Math.round(result.credit_score);
        
        // 更新失信状态
        if (result.is_delinquent) {
            delinquentStatus.textContent = '是';
            delinquentStatus.style.color = '#f44336';
        } else {
            delinquentStatus.textContent = '否';
            delinquentStatus.style.color = '#4caf50';
        }
        
        // 更新风险指示器
        const riskPercentage = result.default_probability * 100;
        riskFill.style.width = `${riskPercentage}%`;
        
        // 根据风险级别设置颜色
        if (riskPercentage < 20) {
            riskFill.style.backgroundColor = '#4caf50';
        } else if (riskPercentage < 50) {
            riskFill.style.backgroundColor = '#ff9800';
        } else {
            riskFill.style.backgroundColor = '#f44336';
        }
        
        // 设置风险评估结论
        if (riskPercentage < 10) {
            riskConclusion.textContent = '风险极低：该客户信用状况优秀，违约可能性很小，建议批准高额度信用。';
            riskConclusion.style.color = '#4caf50';
        } else if (riskPercentage < 20) {
            riskConclusion.textContent = '风险较低：该客户信用状况良好，违约可能性较低，建议批准适当额度信用。';
            riskConclusion.style.color = '#8bc34a';
        } else if (riskPercentage < 35) {
            riskConclusion.textContent = '风险中等：该客户信用状况一般，需要关注其还款能力，建议批准较低额度信用。';
            riskConclusion.style.color = '#ffc107';
        } else if (riskPercentage < 50) {
            riskConclusion.textContent = '风险较高：该客户信用状况欠佳，存在一定的违约风险，建议谨慎批准信用。';
            riskConclusion.style.color = '#ff9800';
        } else {
            riskConclusion.textContent = '风险极高：该客户信用状况较差，违约可能性很大，建议拒绝信用申请或要求提供担保。';
            riskConclusion.style.color = '#f44336';
        }
        
        // 显示结果卡片
        resultCard.classList.remove('hidden');
        
        // 滚动到结果区域
        resultCard.scrollIntoView({ behavior: 'smooth' });
    }
});